<template>
  <el-dialog
    :title="_transitionLanguages('button', 'permissionSetting')"
    v-model="dialogVisible"
    width="800px"
    top="2vh"
    :destroy-on-close="true"
    draggable
    :close-on-click-modal="false"
    @close="$emit('update:visible', false)"
  >
    <el-tabs v-model="activeName" class="demo-tabs">
      <el-tab-pane :label="_transitionLanguages('title', 'menusOperationAuthority')" name="first">
        <el-table
          v-loading="dataGrid.loading"
          :data="dataGrid.data"
          highlight-current-row
          :span-method="objectSpanMethod"
          height="500"
          border
        >
          <el-table-column prop="firstMenu" :label="_transitionLanguages('table', 'FirstLevelMenu')" width="150">
            <template #default="{ row }">
              <el-checkbox v-model="row.checkedFirstMenu" :label="row.firstMenu" @change="changeFirstMenu(row)" />
            </template>
          </el-table-column>

          <el-table-column prop="secondMenu" :label="_transitionLanguages('table', 'secondaryMenu')" width="150">
            <template #default="{ row }">
              <el-checkbox
                v-if="row.secondMenu"
                v-model="row.isCheckedSecondMenu"
                :label="row.secondMenu"
                @change="changeSecondMenu(row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="operateList" :label="_transitionLanguages('table', 'operation')">
            <template #default="{ row }">
              <span v-for="(operate, operateIndex) in row.operateList" :key="operateIndex" style="margin-right: 10px">
                <el-checkbox
                  v-if="operate.name"
                  v-model="operate.checked"
                  :label="operate.name"
                  @change="changeOperateBtn(row)"
                />
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ _transitionLanguages("button", "cancel") }}</el-button>
        <el-button type="primary" @click="saveOperateMenu">
          {{ _transitionLanguages("button", "confirm") }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
// roleMenuSave
import type { TableColumnCtx } from "element-plus";
import { Role } from "@/api/interface/index";

interface SpanMethodProps {
  row: Role.Menu;
  column: TableColumnCtx<Role.Menu>;
  rowIndex: number;
  columnIndex: number;
}

interface OpPermProps {
  visible: boolean;
  roleId: number;
}

interface DataGridProps {
  loading: boolean;
  data: Role.Menu[];
}

const $emit = defineEmits(["update:visible"]);

// 接受父组件参数，配置默认值
const props = withDefaults(defineProps<OpPermProps>(), {
  visible: false,
  roleId: -1
});
let dialogVisible = ref(props.visible);

let dataGrid = ref<DataGridProps>({
  loading: false,
  data: []
});

watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
    if (val) {
      init();
    }
  }
);
watch(
  () => dialogVisible.value,
  val => {
    $emit("update:visible", val);
  }
);

// 语言转换
const _transitionLanguages = (v: string, l: string): string => {
  return transitionLanguages(v, l);
};

// 获取菜单列表
const init = () => {
  const params = {
    roleId: props.roleId
  };
  dataGrid.value.loading = true;
  roleMenuGetByRoleId(params).then((data: any) => {
    dataGrid.value.loading = false;
    dataGrid.value.data = data;

    dataGrid.value.data.forEach(v => {
      const { checkedFirstMenu, checkedSecondMenu } = v;
      v.isCheckedFirstMenu = checkedFirstMenu;
      v.isCheckedSecondMenu = checkedSecondMenu;
      v.operateList = v.operateList || [];
    });

    mergeColumn(dataGrid.value.data, "firstMenu");
  });
};

const activeName = ref("first");

const objectSpanMethod = ({ columnIndex, row }: SpanMethodProps) => {
  if (columnIndex === 0) {
    return {
      rowspan: row.rowSpan,
      colspan: 1
    };
  }
};

// 设置保存菜单的参数
const setSaveParams = (): Role.ReqRoleMenuSave => {
  const menus = dataGrid.value.data.map(item => {
    const { firstMenuId, isCheckedFirstMenu, secondMenuId, isCheckedSecondMenu } = item;
    const operateList = item.operateList.map(son => {
      const { checked, id } = son;
      return {
        isChecked: checked + "",
        id
      };
    });
    return {
      firstMenuId,
      secondMenuId,
      isCheckedFirstMenu: isCheckedFirstMenu + "",
      isCheckedSecondMenu: isCheckedSecondMenu + "",
      operateList
    };
  });

  return {
    roleId: props.roleId,
    menus: menus
  };
};

// 保存操作的菜单
const saveOperateMenu = () => {
  const data = setSaveParams();
  roleMenuSave(data);
  $emit("update:visible", false);
  elMessage();
};

// // 一级菜单值变化
const changeFirstMenu = (item: Role.Menu) => {
  const { checkedFirstMenu, firstMenu } = item || {};
  dataGrid.value.data.forEach((item: Role.Menu) => {
    // 三级菜单二级菜单 跟随一级菜单变化
    if (item.firstMenu === firstMenu) {
      item.isCheckedFirstMenu = checkedFirstMenu;

      // 二级菜单跟随变化
      item.checkedSecondMenu = checkedFirstMenu;
      item.isCheckedSecondMenu = checkedFirstMenu;
      item.operateList.forEach(son => {
        // 三级菜单跟随变化
        son.checked = checkedFirstMenu;
      });
    }
  });
};

// 二级菜单值变化
const changeSecondMenu = (item: Role.Menu) => {
  const { isCheckedSecondMenu, secondMenu, children, firstMenu } = item;
  console.log(children, "children", isCheckedSecondMenu);
  let count = 0;

  for (let v of dataGrid.value.data) {
    // 三级菜单跟随二级菜单变换
    if (v.secondMenu === secondMenu) {
      item.isCheckedFirstMenu = isCheckedSecondMenu;
      v.operateList.forEach(son => {
        son.checked = isCheckedSecondMenu;
      });
    }

    if (firstMenu === v.firstMenu && isCheckedSecondMenu === v.isCheckedSecondMenu) {
      count++;
    }
  }

  // 没有2级菜单时取消一级菜单勾选   有一个二级菜单勾选时勾选上一级菜单
  if ((count === 1 && isCheckedSecondMenu) || count === children) {
    for (let v of dataGrid.value.data) {
      if (v.firstMenu === firstMenu) {
        v.checkedFirstMenu = isCheckedSecondMenu;
      }
    }
  }
};

// 对操作栏进行修改
const changeOperateBtn = (item: Role.Menu) => {
  const isCheckedList = item.operateList.filter(son => son.checked);

  // 是否有操作按钮 一个时对2级菜单进行确定  确保有对应2级菜单权限
  if (isCheckedList.length === 1) {
    item.checkedSecondMenu = true;
    item.isCheckedSecondMenu = true;
  }
};
</script>
